package com.linuxgt.android.smsapp;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private EditText numberText;
    private EditText contentText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        numberText = (EditText) findViewById(R.id.number);
        contentText = (EditText) findViewById(R.id.content);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new smsSendListener());
    }

    private final class smsSendListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            requestPermission();
        }

        /**
         * 申请权限
         */
        private void requestPermission() {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.SEND_SMS)){
                    Toast.makeText(MainActivity.this, R.string.permission, Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                }else {
                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.SEND_SMS},1);
                }
            } else {
                sendSms();
            }
        }

        /**
         * 发送短信
         */
        private void sendSms() {
            String number = String.valueOf(numberText.getText());
            String content = String.valueOf(contentText.getText());
            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> texts = smsManager.divideMessage(content);
            for (String text : texts) {
                smsManager.sendTextMessage(number, null, text, null, null);
            }
            Toast.makeText(MainActivity.this, R.string.success, Toast.LENGTH_LONG).show();
        }
    }
}
